import { logout, getUserInfo } from '@/api/common'
import { setToken, getToken, removeToken } from '@/util/auth'

const user = {
  state: {
    token: getToken(),
    name: '',
    companyFlag: false,
    avatar: '',
    info: {},
    shopPageMap: {},
    buyNum: '',
    searchResult: {},
    searchSite: {} // 搜索结果页地图选择地址
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_COMPANY_FLAG: (state, companyFlag) => {
      state.companyFlag = companyFlag
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    PAGE_MAP: (state, data) => {
      state.shopPageMap = data
    },
    BUY_NUM: (state, data) => {
      state.buyNum = data
    },
    SEARCH_RESULT: (state, data) => {
      state.searchResult = data
    },
    SEARCH_SITE: (state, data) => {
      state.searchSite = data
    }
  },
  actions: {
    setAvatar({ commit }, avatar) {
      return new Promise(() => {
        commit('SET_AVATAR', avatar)
      })
    },
    setName({ commit }, name) {
      return new Promise(() => {
        commit('SET_NAME', name)
      })
    },
    setInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(response => {
          const data = response.data
          commit('SET_INFO', data)
          commit('SET_NAME', data.userNick)
          commit('SET_AVATAR', data.userAvar)
          commit('SET_COMPANY_FLAG', data.companyFlag)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    setInfoParam({ commit }, info) {
      return new Promise(() => {
        commit('SET_INFO', info)
        commit('SET_NAME', info.userNick)
        commit('SET_AVATAR', info.userAvar)
        commit('SET_COMPANY_FLAG', info.companyFlag)
      })
    },
    setToken({ commit }, token) {
      return new Promise(() => {
        commit('SET_TOKEN', token)
        if (token) {
          setToken(token)
        } else {
          removeToken()
        }
      })
    },
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_INFO', {})
          commit('SET_AVATAR', '')
          commit('SET_NAME', '')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_INFO', {})
        commit('SET_AVATAR', '')
        commit('SET_NAME', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
